package org.shijiagen.manager.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.*;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;

@Data
@Component
public class QiNiuOSSUtils {

    private String accessKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    private String secretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    private String bucketName = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";;
    private String domainOfBucket = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";;

    /**
     * 上传图片返回一个临时链接
     * @param objectName
     * @param content
     * @param contentType
     * @return
     */
    public String uploadImage(String objectName, byte[] content,String contentType){
        Auth auth = Auth.create(accessKey,secretKey);
        BucketManager bucketManager = getBucketManager();
        try {
            boolean exist = Arrays.asList(bucketManager.buckets()).contains(bucketName);
            if (!exist){
                bucketManager.createBucket(bucketName,"z2");
            }
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
        String upToken = auth.uploadToken(bucketName);
        UploadManager uploadManger = getUploadManger();
        try {
            uploadManger.put(content,objectName,upToken,null,contentType,false);

            String encodedFileName = URLEncoder.encode(objectName, StandardCharsets.UTF_8).replace("+", "%20");
            return String.format("%s/%s", domainOfBucket, encodedFileName);
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下载文件到本地存储
     * @param objectName
     * @param localFile
     */
    public void downFile(String objectName, String localFile){
        try {
            String encodedFileName = URLEncoder.encode(objectName, StandardCharsets.UTF_8).replace("+", "%20");
            String url =String.format("%s/%s", domainOfBucket, encodedFileName);
            HttpClient client = HttpClient.newBuilder().build();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url)).build();
            client.send(request, HttpResponse.BodyHandlers.ofFile(Paths.get(localFile)));
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除云服务上的文件
     * @param objectName
     */
    public void deleteFile(String objectName){
        BucketManager bucketManager = getBucketManager();
        try {
            bucketManager.delete(bucketName,objectName);
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
    }

    private UploadManager getUploadManger(){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        cfg.useHttpsDomains = false;
        return new UploadManager(cfg);
    }

    private BucketManager getBucketManager(){
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        cfg.useHttpsDomains = false;
        Auth auth = Auth.create(accessKey,secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            boolean exist = Arrays.asList(Optional.ofNullable(bucketManager.buckets()).orElse(new String[]{})).contains(bucketName);
            if (!exist){
                bucketManager.createBucket(bucketName,"z2");
            }
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
        return bucketManager;
    }
}
